<template>
  <div>
    <ChatPage :agentId="agentId"></ChatPage>
    <AgentListView 
      :dialogVisible="dialogVisible" 
      :list="agentList"
      @tab-close="handelTabClose"
      @tab-click="handelTabClick"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import ChatPage from '@/views/webapp/pc/index.vue'
import AgentListView from '@/views/webapp/pc/AgentList.vue'
import ChatBi from '@/api/chatbi'
import { useRoute, useRouter } from 'vue-router'
import useStore from '@/stores'
import bus from '@/bus'

const { chatbi } = useStore()
const route = useRoute()
const router = useRouter()

defineOptions({
  name: 'ChatPage'
})
const agentList = ref<any[]>([])
const agentId = ref<string>('') /** 当前选中的 agentId */
const dialogVisible = ref<boolean>(false)

/**
 * 更新 URL 查询参数中的 agentId
 * @param newAgentId 新的 agentId 值
 */
function updateUrlAgentId(newAgentId: string) {
  router.replace({
    query: { ...route.query, agentId: newAgentId }
  })
}

/**
 * 获取默认的 agentId
 * 优先级：
 * 1. URL 参数中获取
 * 2. localStorage 中获取
 * 3. 默认选择第一个 agent
 * @param agents agent 列表
 * @returns 默认的 agentId
 */
function getDefaultAgentId(agents: any[]) {
  if (!Array.isArray(agents) || agents.length === 0) return ''

  // 从 URL 中获取
  const urlAgentId = route.query.agentId as string | undefined
  if (urlAgentId && agents.some((el) => `${el.id}` === urlAgentId)) {
    localStorage.setItem('agentId', urlAgentId)
    return urlAgentId
  }

  // 从 localStorage 中获取
  const storedAgentId = localStorage.getItem('agentId')
  if (storedAgentId && agents.some((el) => `${el.id}` === storedAgentId)) {
    updateUrlAgentId(storedAgentId)
    return storedAgentId
  }

  // 默认选择第一个 agent
  const defaultAgentId = `${agents[0].id}`
  updateUrlAgentId(defaultAgentId)
  localStorage.setItem('agentId', defaultAgentId)
  return defaultAgentId
}

/**
 * 获取所有 agent 并设置默认 agentId
 */
function getAllAgent() {
  ChatBi.getAgentList().then((res) => {
    if (res.data.length > 0) {
      const list = res.data?.filter((el:any)=> el.status === 1 )
      const id = getDefaultAgentId(list)
      agentId.value = id
      agentList.value = list
    }
  })
}

function handelTabClose() {
  dialogVisible.value = false
}


function handelTabClick(item: any) {
  ChatBi.saveChat({agentId: item.id, chatName:'新问答对话'}).then((res: any) => { 
    localStorage.setItem('chatId', res.data)
    localStorage.setItem('agentId', item.id)
    updateUrlAgentId(item.id)
    setTimeout(()=> {
      window.location.reload()
    },0)
  })
}

watch(() => agentId.value,(newVal) => {
  if(newVal){
    // 设置当前选中的agent
    agentList.value.forEach((item) => {
      if(`${item.id}` === `${newVal}`) {
        chatbi.setAgent({...item})
      }
    })
  }
})

onMounted(() => {
  getAllAgent()

  bus.on('webapp-chat-open', () => {
    dialogVisible.value = true
  })
})
</script>